package org.client;

import java.net.ServerSocket;
import java.net.Socket;

import org.client.chat.ITalkServer;
import org.eclipse.swt.widgets.Display;

public class PeerServerSocket extends Thread{
	
	private ServerSocket serverSocket;
	private int port = 1501;
	private String loginName;
	private byte[] key;
	private Socket tempSocket;
	public void setKey(byte[] key) {
		this.key = key;
	}
	public int connect(String loginName)
	{
		
		this.loginName = loginName;
		boolean isBind = false;
		while(!isBind)
		{
			try {
				serverSocket = new ServerSocket(port);
				isBind = true;
			} catch (Exception e) {
				port++;
			}
		}
		return port;
	}
	@Override
	public void run() {
		super.run();
		
			try{
				while(true)
				{
					tempSocket = serverSocket.accept();
					//new ServerChatingWindow(tempSocket,loginName,key);
					Display.getDefault().asyncExec( new Runnable()
					{
						@Override
						public void run() {
							new ITalkServer(tempSocket,loginName,key);							
						}
						
					});

				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		
		
	}
}
